package io.gitee.yth.design.pattern.test.core.pattern.structural.proxy.cglibproxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @author yth
 * @since 2023-04-28-0:13
 */
public class CglibProxyFactory implements MethodInterceptor {

    private final Object target;

    public CglibProxyFactory(Object target) {
        this.target = target;
    }

    /**
     * @return 返回 <code>target</code> 的代理对象
     */
    public Object getProxyInstance() {
        final Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {

        System.out.println("--cglib proxy start--");

        System.out.println("args = " + Arrays.toString(args));
        if (args.length > 0 && args[0] instanceof Integer)
            args[0] = 7;
        final Object retVal = method.invoke(target, args);

        System.out.println("return = " + retVal);
        System.out.println("--cglib proxy commit--");
        if (retVal instanceof Integer)
            return 7 + (int) retVal;
        return retVal;
    }
}
